package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

// 初始化连接
func initDB() (err error) {
	// DSN:Data Source Name
	host := configMap["mysql"]["host"]
	port := configMap["mysql"]["port"]
	user := configMap["mysql"]["user"]
	password := configMap["mysql"]["password"]
	dbName := configMap["mysql"]["db"]
	// dsn := "user:password@tcp(127.0.0.1:3306)/dbname"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, password, host, port, dbName)
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	// defer db.Close() // 注意这行代码要写在上面err判断的下面
	return nil
}

// 插入告警
func insertRow(a Alert, str string) error {
	err := initDB()
	if err != nil {
		fmt.Printf("init db connection failed, err:%v\n", err)
		return err
	}
	sqlStr := `insert into alert_history
			   (alert_type, alert_status, alert_name, instance, description, summary, startsat, endsat) 
			   values (?,?,?,?,?,?,?,?)
			`
	_, err = db.Exec(sqlStr, str, a.status, a.alertname, a.instance, a.description, a.summary,
		a.startsAt.Format("2006-01-02 15:04:05"),
		a.endsAt.Format("2006-01-02 15:04:05"))
	if err != nil {
		fmt.Printf("insert failed, err:%v\n", err)
		return err
	}
	// _, err = ret.LastInsertId() // 新插入数据的id
	// if err != nil {
	// 	fmt.Printf("get lastinsert ID failed, err:%v\n", err)
	// 	return err
	// }
	// fmt.Printf("insert success, the id is %d.\n", theID)
	defer db.Close()
	return nil
}
